package com.heue.voice.util;

import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.ArrayList;

public class HandlerUtil {
    public interface HandlerProgressListener {
        void onStart(int max);
        void onProgress(int progress);
        void onFinish();
    }
    private final HandlerProgressListener handlerProgressListener;
    public HandlerUtil(HandlerProgressListener handlerProgressListener) {
        this.handlerProgressListener = handlerProgressListener;
    }

    /*
    public void setHandlerProgressListener(HandlerProgressListener handlerProgressListener) {
        this.handlerProgressListener = handlerProgressListener;
    }
    */

    private MediaExtractor mediaExtractor;
    //一个变量，资源路径，保存路径，文件绝对路径
    public void initMediaDecode(String srcPath, String savePath, String filePath) {
        //long now = System.currentTimeMillis();
        //boolean isSucceed = false;
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File file1 = new File(filePath);
            if (file1.exists()) {
                file1.delete();
            }
            file1.createNewFile();

            mediaExtractor = new MediaExtractor();
            mediaExtractor.setDataSource(srcPath);
            for (int i = 0; i < mediaExtractor.getTrackCount(); i++) {
                MediaFormat format = mediaExtractor.getTrackFormat(i);
                String mime = format.getString(MediaFormat.KEY_MIME);
                if (mime.startsWith("audio")) {
                    mediaExtractor.selectTrack(i);
                    ByteBuffer inputBuffer = ByteBuffer.allocate(100 * 1024);
                    List<byte[]> resultList = new ArrayList<>();
                    while (true) {
                        int readSampleCount = mediaExtractor.readSampleData(inputBuffer, 0);
                        if (readSampleCount < 0) {
                            break;
                        }
                        byte[] buffer = new byte[readSampleCount];
                        inputBuffer.get(buffer);
                        byte[] newbuff = new byte[readSampleCount + 7];
                        addADTStoPacket(newbuff, readSampleCount + 7);
                        System.arraycopy(buffer, 0, newbuff, 7, readSampleCount);
                        resultList.add(newbuff);
                        //设置进度条值
                        inputBuffer.clear();
                        mediaExtractor.advance();
                    }
                    //fe.flush();
                    //fe.close();
                    //bos.flush();
                    //bos.close();
                    saveFile(file1, resultList);
                }
            }
            //
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //long end = System.currentTimeMillis();
            //Log.i("耗时：", String.valueOf(end - now));
            mediaExtractor.release();
            mediaExtractor = null;
        }
    }

    private void saveFile(File file, List<byte[]> buffer) {
        try {
            handlerProgressListener.onStart(buffer.size());
            FileOutputStream fe=new FileOutputStream(file, true);
            BufferedOutputStream bos = new BufferedOutputStream(fe);
            int i = 0, n = 0;
            for (byte[] the : buffer) {
                bos.write(the, 0, the.length);
                if (n == 5) {
                    n = 0;
                    i = i + 5;
                    handlerProgressListener.onProgress(i);
                }
                else  n++;
            }
            handlerProgressListener.onProgress(buffer.size());
            bos.flush();
            bos.close();
        } catch (Exception e) {
            return;
        }
        handlerProgressListener.onFinish();
    }

    //添加adts头
    private void addADTStoPacket(byte[] packet, int packetLen) {
        int profile = 2;  //AAC LC
        int freqIdx = 4;  //影响音频的速度
        int chanCfg = 1;  //CPE
        /*int avpriv_mpeg4audio_sample_rates[] = {96000, 88200, 64000, 48000, 44100, 32000,24000, 22050, 16000, 12000, 11025, 8000, 7350};
         channel_configuration: 表示声道数chanCfg
         0: Defined in AOT Specifc Config
         1: 1 channel: front-center
         2: 2 channels: front-left, front-right
         3: 3 channels: front-center, front-left, front-right
         4: 4 channels: front-center, front-left, front-right, back-center
         5: 5 channels: front-center, front-left, front-right, back-left, back-right
         6: 6 channels: front-center, front-left, front-right, back-left, back-right, LFE-channel
         7: 8 channels: front-center, front-left, front-right, side-left, side-right, back-left, back-right, LFE-channel
         8-15: Reserved
         */
        packet[0] = (byte) 0xFF;
        packet[1] = (byte)0xF1;
        packet[2] = (byte) (((profile - 1) << 6) + (freqIdx << 2) + (chanCfg >> 2));
        packet[3] = (byte) (((chanCfg & 3) << 6) + (packetLen >> 11));
        packet[4] = (byte) ((packetLen & 0x7FF) >> 3);
        packet[5] = (byte) (((packetLen & 7) << 5) + 0x1F);
        packet[6] = (byte) 0xFC;
    }

}
